<?php
class User_model extends CI_Model {
	
	public function get_user_list()
	{
		$sql = 'SELECT * FROM user';
		$query = $this->db->query($sql);
		
		return $query->result();
	}
	
	public function get_user_by_key($key)
	{
		$sql = 'SELECT * FROM user WHERE validateKey=? LIMIT 1';
		$query = $this->db->query($sql, array($key));
		
		return $query->num_rows > 0 ? $query->row() : false;
	}
	
	public function get_user_by_mail($mail)
	{
		$sql = 'SELECT * FROM user WHERE mail=? LIMIT 1';
		$query = $this->db->query($sql, array($mail));
		
		return $query->num_rows > 0 ? $query->row() : false;
	}
	
	public function get_user_by_mail_password($mail, $password)
	{
		$sql = 'SELECT * FROM user WHERE mail=? AND password=? LIMIT 1';
		$query = $this->db->query($sql, array($mail, md5($password)));
		
		return $query->num_rows > 0 ? $query->row() : false;
	}
	
	public function add_user($mail, $password)
	{
		$sql = 'INSERT INTO user (mail, password, registerTime, validateKey, activated) VALUES (?, ?, now(), ?, 0)';
		$query = $this->db->query($sql, array($mail, md5($password), md5($mail)));
		
		return $this->db->affected_rows() > 0 ? $this->db->insert_id() : false;
	}
	
	public function validate_user($key)
	{
		$sql = 'UPDATE user SET activated=1 WHERE validateKey=? LIMIT 1';
		$query = $this->db->query($sql, array($key));
		
		return $this->db->affected_rows() > 0;
	}
	
	public function change_password($mail, $password)
	{
		$sql = 'UPDATE user SET password=? WHERE mail=? LIMIT 1';
		$query = $this->db->query($sql, array(md5($password), $mail));
		
		return $this->db->affected_rows() > 0;
	}
}
?>